package com.maxiaoke.boot.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.maxiaoke.boot.bean.User;
import com.maxiaoke.boot.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.batch.BatchProperties;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.Arrays;
import java.util.List;

@Slf4j
@Controller
public class TableController {

    @Autowired(required = false)
    JdbcTemplate jdbcTemplate;

    @GetMapping("/basic_table")
    public String basic_table() {
        Long aLong = jdbcTemplate.queryForObject("select count(*) from vtiger_users", Long.class);
        log.info("记录总数：{}", aLong);

        return "table/basic_table";
    }

    @Autowired
    UserService userService;

    @GetMapping("/dynamic_table")
    public String dynamic_table(@RequestParam(value = "pn",defaultValue = "1") Integer pn, Model model) {

        /**
         * 分页查询数据
         * Page<User> userPage = new Page<>(pn, 2);
         * 第一个参数pn表示当前第几页，由请求参数带进来
         * 第二个参数2 表示每页显示几条数据
         *
         * userService.page(userPage,null);
         * 第一个参数为对User表进行分页
         * 第二个参数为分页查询条件
         */
        Page<User> userPage = new Page<>(pn, 2);

        //返回的page对象为分页的查询结果
        Page<User> page = userService.page(userPage, null);

        model.addAttribute("users",page);

        return "table/dynamic_table";
    }

    @GetMapping("/responsive_table")
    public String responsive_table() {

        return "table/responsive_table";
    }

    @GetMapping("/editable_table")
    public String editable_table() {

        return "table/editable_table";
    }

    /**
     * 删除用户
     * @return
     */
    @GetMapping("/user/delete/{id}")
    public String deleteUser(@PathVariable("id") Long id,
                             @RequestParam(value = "pn",defaultValue = "1") Integer pn,
                             RedirectAttributes ra){

        userService.removeById(id);

        //重定向,url带上pn的值
        ra.addAttribute("pn",pn);

        return "redirect:/dynamic_table";
    }

}
